package components

import (
	"crypto/md5"
	"encoding/hex"
	"math/rand"
	"net/http"
	"time"
)

// Sequence 生成序列
// n: 序列长度
func Sequence(n int) []int {
	result := make([]int, n)
	for i := 0; i < n; i++ {
		result[i] = i + 1
	}
	return result
}

// Md5 生成32位MD5哈希值
// text: 要加密的文本
func Md5(text string) string {
	ctx := md5.New()
	ctx.Write([]byte(text))
	return hex.EncodeToString(ctx.Sum(nil))
}

// GetRandomString 生成随机字符串
// length: 字符串长度
func GetRandomString(length uint) string {
	str := "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
	bytes := []byte(str)
	result := []byte{}
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	var i uint
	for i = 0; i < length; i++ {
		result = append(result, bytes[r.Intn(len(bytes))])
	}
	return string(result)
}

// DatetimeToTimeZone datetime格式时间转时间戳
// timeString: 时间字符串，格式为"2006-01-02 15:04:05"
func DatetimeToTimeZone(timeString string) (timeZone int64) {
	timeLayout := "2006-01-02 15:04:05"
	tm2, err := time.Parse(timeLayout, timeString)
	if err != nil {
		return 0
	}
	timeZone = tm2.Unix()
	return
}

// GetCurrentUrl 获取当前请求的完整URL
func GetCurrentUrl(r *http.Request) string {
	scheme := "http"
	if r.TLS != nil {
		scheme = "https"
	}
	return scheme + "://" + r.Host + r.RequestURI
}
